<?php
namespace Common\Behavior;

class CheckPurviewBehavior extends \Think\Behavior{
	//行为执行入口

	public function run(&$param){
		#获得路径
		$a    = ACTION_NAME; //方法名
		$c    = CONTROLLER_NAME;  //控制器名
		$m    = MODULE_NAME;  //分组名称
		$return_url = trim($m."/".$c."/".$a,'/');//,


		$url = strtolower($return_url);

		$this->_getMenus();
		//后台管理员访问前台页面,获取着前台管理员访问后台页面
		if($m != $_SESSION['module_name'] && !in_array($url,C('PAGE_NO_LOGIN'))){
			$this->_redirect();
		}
		#登陆前 不需要权限的页面
		if(in_array($url,C('PAGE_NO_LOGIN'))){
			return ;
		}

		#登陆后 不需要权限的页面
		if(in_array($url,C('PUBLIC_PAGE'))){
			return ;
		}

		if(!in_array($url,$_SESSION['purview'])){
			$this->_redirect();
		}

	}
	protected function _getMenus(){

		$menus = C('menus');
		$role  = C('role_purview.'.$_SESSION['USER']['role_id']);
		$purview = array();
		foreach (C('purview_list') as $pk=>$pv){
			if(in_array($pk,$role)){
				$purview[$pk] = $pv['url'];
			}
		}
		foreach ($menus as $mk=>$mv){
			$purl = strtolower($mv['purl']);
			if(!in_array($purl,$purview)){
				unset($menus[$mk]);
				continue;
			}
			foreach ($mv['item'] as $k=>$v){
				$purl = strtolower($v['purl']);
				if(!in_array($purl,$purview)){
					unset($menus[$mk][$k]);
				}
			}
		}
		session('menus',$menus);
		session('purview',$purview);
	}

	/**
	 * 页面跳转
	 */
	protected function _redirect(){
		$redirect_url = U($_SESSION['module_name']."/Index/index");
		header("Content-Type:text/html;charset=utf-8");
		$error_msg = "无权限访问当前页面\n页面跳转中...\n<a href='".$redirect_url."'>返回首页</a>";
		redirect($redirect_url,5,$error_msg);
	}
}